//
//  Person.m
//  relevanceKVO
//
//  Created by ZhangSai on 2021/8/20.
//

#import "Person.h"

@implementation Person

static void *PersonNameContext = &PersonNameContext;

- (void)dealloc{
    [self removeObserver:self forKeyPath:@"downloadProgress"];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self addObserver:self forKeyPath:@"downloadProgress" options:NSKeyValueObservingOptionNew context:NULL];
    }
    return self;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
  // 改变的相关值
    NSLog(@"%@",change);
}

// 下载进度 -- writtenData/totalData
// 因为"totalData", @"writtenData"的值的改变，会影响到下载进度，通过这个方法，可以关联监听这两个值
+ (NSSet<NSString *> *)keyPathsForValuesAffectingValueForKey:(NSString *)key{
    NSSet *keyPaths = [super keyPathsForValuesAffectingValueForKey:key];
    if ([key isEqualToString:@"downloadProgress"]) {
        NSArray *affectingKeys = @[@"totalData", @"writtenData"];
        keyPaths = [keyPaths setByAddingObjectsFromArray:affectingKeys];
    }
    return keyPaths;
}

// 重写 downloadProgress 的 getter 方法
- (NSString *)downloadProgress{
    // 下载进度 = 已下载数量 / 总数量
    return [[NSString alloc] initWithFormat:@"%f",1.0f*self.writtenData/self.totalData];
}

@end
